package net.bolue.console.model;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import net.bolue.sysmng.db.DbOpUtil;
import net.bolue.sysmng.exception.BolueException;
import net.bolue.sysmng.model.ColInfoModel;
import net.bolue.sysmng.tblbean.ColInfo;
import net.bolue.sysmng.tblbean.DelRes;
import net.bolue.web.mvc.ActionResult;
import net.bolue.web.util.RequestUtil;

/**
 * 删除操作业务
 * @author Administrator
 *
 */
public class DeleteModel extends BusiBase{

	private DelRes delRes = null;
	private List<ColInfo> colInfoList = null;
	
	public DeleteModel(){}
	
	public DeleteModel(HttpServletRequest request,DelRes delRes)throws BolueException{
		super(request);
		this.delRes = delRes;
	}
	
	/**
	 * 初始化表列
	 * @throws BolueException
	 */
	private void init()throws BolueException{
		if(this.delRes==null){
			return;
		}
		String tableName = this.delRes.getTableName();
		ColInfoModel colInfoModel = new ColInfoModel(request);
		List<ColInfo> colInfoList = colInfoModel.getColInfoList(this.delRes.getSubSys(), tableName);
		this.colInfoList = colInfoList;
	}
	
	/**
	 * 删除业务主方法
	 * @return
	 * @throws BolueException
	 */
	public ActionResult delete()throws BolueException{
		this.init();
		Integer delType = this.delRes.getDeleteType();
		if(delType==1){
			return deleteByTable();
		}
		return null;
	}
	
	/**
	 * 通过表删除
	 * @return
	 * @throws BolueException
	 */
	public ActionResult deleteByTable() throws BolueException{
		Map<String,Object> whereMap = new HashMap<String,Object>();
		if(this.colInfoList==null){
			return null;
		}
		for(ColInfo colInfo : this.colInfoList){
			String keyName = colInfo.getColName();
			String keyValue = RequestUtil.getParamValue(request, "col_"+keyName);
			if(keyValue==null){
				continue;
//				throw new BolueException(1, "在request中，必须提供参数"+"col_"+keyName+"!");
			}
			whereMap.put(keyName, keyValue);
		}
		String tableName = this.delRes.getTableName();
		String subSys = this.delRes.getSubSys();
		DbOpUtil dbOpUtil = new DbOpUtil(subSys);
		dbOpUtil.delete(tableName, whereMap);
		
		ActionResult actionResult = new ActionResult();
		boolean result = true;
		actionResult.setResult(result);
		return actionResult;
	}
}
